package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;
import org.xutils.DbManager;

import java.util.ArrayList;
import java.util.List;

import zj.com.adapter.DshDetailAdapter;
import zj.com.adapter.DzgDetailAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.interfaze.CallData;
import zj.com.model.Dic;
import zj.com.model.DjcModel;
import zj.com.model.Dzg;
import zj.com.model.DzgDetail;
import zj.com.model.DzgDetailDB;
import zj.com.model.DzgInspectTask;
import zj.com.model.JcxDB;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.Constants;
import zj.com.util.DateUtil;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.util.SharedPreferencesUtil;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/12.
 *
 * 待审核的详情
 */
public class DshDetailActivity extends  BaseActivity implements View.OnClickListener,CallData{


    public TextView title_name,right_tv;
    public ImageView left_iv;
    public ListView listView;
    public List<DzgInspectTask> list;
    public DshDetailAdapter adapter;
    public DbManager dbManager;

    public TextView rw_tv,yh_tv,jczy_tv,jcx_tv,gs_tv,xm_tv,jcType_tv,end_date_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dsh_detail);
        dbManager = DBUtil.getInstance(this).getDBManager();
        initView();
        initData();
    }

    public void initView(){
        title_name = (TextView) findViewById(R.id.title_name);
        title_name.setText("审批详情");
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setOnClickListener(this);
        right_tv.setVisibility(View.GONE);
        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setOnClickListener(this);
        left_iv.setVisibility(View.VISIBLE);

        listView = (ListView) findViewById(R.id.listView);

        rw_tv = (TextView) findViewById(R.id.rw_value_tv);
        yh_tv = (TextView) findViewById(R.id.yh_value_tv);
        jczy_tv = (TextView) findViewById(R.id.jczy_vale_tv);
        jcx_tv = (TextView) findViewById(R.id.jcx_value_tv);
        gs_tv = (TextView) findViewById(R.id.gs_value_tv);
        xm_tv = (TextView) findViewById(R.id.xm_value_tv);
        jcType_tv = (TextView) findViewById(R.id.jc_type_value_tv);
        end_date_tv = (TextView) findViewById(R.id.end_date_value_tv);

    }

   public Dzg dzg;
    public void initData(){
        list = new ArrayList<DzgInspectTask>();

        adapter = new DshDetailAdapter(list,this);
        adapter.setCallData(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent =     new Intent(DshDetailActivity.this, DshDetailEditActivity.class);

                intent.putExtra("task",list.get(position));
                startActivity(intent);


            }
        });

        dzg = (Dzg) getIntent().getSerializableExtra("detail");
        InspectionID =  getIntent().getStringExtra("InspectionID");
        InspectionItemID =  getIntent().getStringExtra("InspectionItemID");
    }
    public String InspectionID="";
    public String InspectionItemID ="";
    @Override
    protected void onResume() {
        super.onResume();
        if(!TextUtils.isEmpty(InspectionID)){
            obtainData(InspectionID,InspectionItemID);

        }else{
            if(dzg == null)
            {

                finish();
                return;
            }
            obtainData(dzg.getInspectionID() + "", dzg.getInspectItemID() + "");

        }
    }

    public DzgDetail detail;

    public void obtainData(final String inspectionID, final String inspectionItemID){


        dialog = DialogUtil.createProgressDialog(this, "提示", "数据获取中..");

        NetManager.getInstance(this).GetPenddingAuditRepairRecordDetail(inspectionID+"", inspectionItemID+"", new OnResponseListener<DzgDetail>() {
            @Override
            public void onComplete(boolean isOK,DzgDetail detail, int errorCode, String errorMsg) {

                if(inspectionID != null && detail == null){

                    Toast.makeText(DshDetailActivity.this,"该任务已处理",Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }
                try {

                    list.clear();
                    if (detail != null) {
                        DzgDetailDB detailDB = new DzgDetailDB();
                        if(dzg != null){
                            detailDB.setInspectionID(dzg.getInspectionID());
                            detailDB.setInspectionItemID(dzg.getInspectItemID());
                        }else{
                            detailDB.setInspectionID(Integer.parseInt(inspectionID));
                            detailDB.setInspectionItemID(Integer.parseInt(inspectionItemID));
                        }

                        detailDB.setRiskID(detail.getRiskID());
                        ZjApplication.dzgDetailDB = detailDB;
                        rw_tv.setText(detail.getInspectTaskName());
                        Dic riskDic = dbManager.selector(Dic.class).where("dic_value", "=", detail.RiskType + "").and("dic_type", "=", Constants.RiskType).findFirst();
                        if(riskDic != null){
                            yh_tv.setText(riskDic.getName());
                        }
                        Dic inspectDic = dbManager.selector(Dic.class).where("dic_value", "=", detail.getInspectType() + "").and("dic_type", "=", Constants.InspectType).findFirst();
                        if(inspectDic != null){
                            jcType_tv.setText(inspectDic.getName());
                        }
                        jcx_tv.setText(detail.getInspectItemName());
                        gs_tv.setText(detail.getInspectOrgName());
                        xm_tv.setText(detail.getInspectProjectName());
                        jczy_tv.setText(detail.getInspectProfessionName());
                        end_date_tv.setText(DateUtil.formatStrimgDate2(detail.getDeadLine().replace("T", " ")));

                        List<DzgInspectTask> tasks = detail.getTaskList();
                        list.addAll(tasks);
                        adapter.setDataChange(tasks);
                        setListViewHeightBasedOnChildren(listView);
                    }
                }catch(Exception e){

                    LogUtils.getInstance().error(e.toString());
                }
                dialog.dismiss();
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.right_tv:

                break;
        }
    }

    @Override
    public void call(Object obj,String state) {

        DzgInspectTask task = (DzgInspectTask) obj;
        doRepair(state, task);
    }

    public ProgressDialog dialog ;
    public void doRepair(String state,DzgInspectTask task){
        String uid = (String) SharedPreferencesUtil.getData(this, "uid", "");

        JSONObject obj = new JSONObject();
        try {
            obj.put("UserID", uid);
            obj.put("InspectionID", ZjApplication.dzgDetailDB.getInspectionID() + "");
            obj.put("InspectTaskID", task.getInspectTaskID()+"");
            obj.put("AuditDesc", "");
            obj.put("AuditResult", state+"");
        }catch(Exception e){

        }

        dialog = DialogUtil.createProgressDialog(this,"提示","操作中...");
        String request = obj.toString();
        NetManager.getInstance(this).AuditRepairRecord(request, new OnResponseListener<List<JcxDB>>() {
            @Override
            public void onComplete(boolean isOK, List<JcxDB> result, int errorCode, String errorMsg) {

                dialog.dismiss();
                if (isOK) {
                    Toast.makeText(DshDetailActivity.this, "成功", Toast.LENGTH_SHORT).show();


                } else {
                    Toast.makeText(DshDetailActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                }
                finish();
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

                Toast.makeText(DshDetailActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));


        listView.setLayoutParams(params);
    }
}
